package com.example.zhou.filehelper;

import android.content.Context;
import android.media.MediaMetadata;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.text.TextUtils;

import com.example.zhou.musicmodel.MusicBean;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by 11065 on 2016/11/11.
 */

public class FileUtil {

    private final static String Unknow = "unknow";

    public FileUtil() {

    }

    public static List<MusicBean> getMusic(List<String> fileList) {
        List<MusicBean> musicBeenlist = new ArrayList<>();
        for (String string : fileList) {
            MusicBean musicBean = getMusic(string);
            musicBeenlist.add(musicBean);
        }
        return musicBeenlist;
    }


    private static MusicBean getMusic(String s) {
        File file = new File(s);
        if (file.length() == 0) return null;
        int duration;
        MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();

        metadataRetriever.setDataSource(file.getAbsolutePath());
        final String name = getMetadata(metadataRetriever, MediaMetadataRetriever.METADATA_KEY_TITLE, file.getName());
        final String ARTIST = getMetadata(metadataRetriever, MediaMetadataRetriever.METADATA_KEY_ARTIST, file.getName());
        String keyDuration = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
        // ensure the duration is a digit, otherwise return null song
        if (keyDuration == null || !keyDuration.matches("\\d+")) return null;
        duration = Integer.parseInt(keyDuration);
        String Ablum = getMetadata(metadataRetriever, MediaMetadataRetriever.METADATA_KEY_ALBUM, Unknow);
        String data = getMetadata(metadataRetriever, MediaMetadataRetriever.METADATA_KEY_DATE, Unknow);
        String Display_name = getMetadata(metadataRetriever, MediaMetadataRetriever.METADATA_KEY_AUTHOR, Unknow);
        metadataRetriever.release();
        return new MusicBean(Ablum, ARTIST, data, Display_name, duration + "", file.getAbsolutePath(), name, name);

    }


    private static String getMetadata(MediaMetadataRetriever retriever, int key, String defaultValue) {
        String value = retriever.extractMetadata(key);
        if (TextUtils.isEmpty(value)) {
            value = defaultValue;
        }
        return value;
    }
}
